package view;

import dao.User;
import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html; charset=utf-8");
        req.setCharacterEncoding("utf-8");
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        if (username==null||password==null||"".equals(username)||"".equals(password)){
            String html="<h3>登录失败 缺少用户名和密码</h3>";
            resp.getWriter().write(html);
            return;
        }
        UserDao userDao=new UserDao();
        User user=userDao.selectByName(username);
        if (user==null){
            String html="<h3>登录失败 用户不存在</h3>";
            resp.getWriter().write(html);
            return;
        }
        else if (!user.getPassword().equals(password)){
            String html="<h3>登录失败 密码错误</h3>";
            resp.getWriter().write(html);
            return;
        }
        HttpSession session=req.getSession(true);
        session.setAttribute("user",user);
        resp.sendRedirect("blog_list.html");
    }
}
